package com.qc31.monitorlib.ui.carmonitor

import android.graphics.drawable.ColorDrawable
import android.view.*
import android.widget.PopupWindow
import android.widget.RadioGroup
import androidx.activity.viewModels
import autodispose2.autoDispose
import com.qc31.baselib.base.BaseActivity
import com.qc31.baselib.utils.toast
import com.qc31.comlib.Keys
import com.qc31.comlib.TimeUtil
import com.qc31.comlib.UrlUtil
import com.qc31.comlib.entity.HistoryVideo
import com.qc31.monitorlib.R
import com.qc31.monitorlib.databinding.ActivityHistoryTmnVideoBinding
import com.qc31.monitorlib.ui.video.CustomVideoManager
import com.qc31.monitorlib.ui.video.view.TmnVideo
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack
import com.shuyu.gsyvideoplayer.video.base.GSYVideoView

/** @Author Jasper @Time 2020/9/29 @Desc 终端视频播放 */
class TmnVideoActivity :
    BaseActivity<ActivityHistoryTmnVideoBinding>(ActivityHistoryTmnVideoBinding::inflate) {
    val mViewModel: TmnVideoViewModel by viewModels()

    override fun initView() {
        val result: HistoryVideo.Result =
            intent.getSerializableExtra(Keys.INTENT_DATA) as HistoryVideo.Result
        mViewModel.carId = intent.getStringExtra(Keys.INTENT_CAR_ID) ?: ""
        mViewModel.videoEntity = result
        initPlayPopup()
        initMultiplePopup()
        initVideo()
    }

    override fun setListener() {
        binding.hTmnVideo.dismissControlTime = 4000
        binding.hTmnVideo.tvTmnPlayOperate.setOnClickListener {
            if (mViewModel.videoState != 5) {
                mViewModel.resumeVideo()
            } else {
                val location = IntArray(2)
                binding.hTmnVideo.tvTmnPlayOperate.getLocationOnScreen(location)
                playPopup?.showAtLocation(
                    binding.hTmnVideo.tvTmnPlayOperate, Gravity.NO_GRAVITY,
                    location[0], location[1] - measuredHeight
                )
            }
        }
        binding.hTmnVideo.setDismissState(object : TmnVideo.DismissState {
            override fun onDismiss() {
                playPopup?.dismiss()
            }
        })

        binding.hTmnVideo.tvTmnMultiple.setOnClickListener {
            val location = IntArray(2)
            binding.hTmnVideo.tvTmnMultiple.getLocationOnScreen(location)
            multiplePopup?.showAtLocation(
                binding.hTmnVideo.tvTmnMultiple, Gravity.NO_GRAVITY,
                location[0], location[1] - measuredMultipleHeight
            )
        }
    }

    private fun initVideo() {
        binding.hTmnVideo.setVideoTitle("${intent.getStringExtra(Keys.INTENT_TITLE)}--${getString(R.string.desc_video_pass) + mViewModel.videoEntity?.channel} ")
        binding.hTmnVideo.setSeekBarState(
            TimeUtil.instance.getDiffLockTime(
                mViewModel.videoEntity?.startTime ?: "", mViewModel.videoEntity?.endTime ?: ""
            )
        )
        binding.hTmnVideo.startPlay.setOnClickListener {
            if (binding.hTmnVideo.currentState == GSYVideoView.CURRENT_STATE_PLAYING) {
                binding.hTmnVideo.showProgress(false)
                mViewModel.pauseVideo()
            } else {
                if (mViewModel.videoState == 0) {

                    binding.hTmnVideo.setUpLazy(
                        mViewModel.playParam(), false, null, null,
                        getString(R.string.desc_video_pass) + mViewModel.videoEntity?.channel
                    )
                    binding.hTmnVideo.startPlayLogic()
                    binding.hTmnVideo.showProgress(false)
                } else {
                    mViewModel.resumeVideo()
                }
            }
        }
        binding.hTmnVideo.progressSub.hide().autoDispose(scopeProvider).subscribe {
            mViewModel.endTime(it)
        }
        binding.hTmnVideo.tvBack.setOnClickListener {
            mViewModel.stopPlay()
            binding.hTmnVideo.release()
            CustomVideoManager.instance.releaseAllVideos()
            finish()
        }
        mViewModel.toastObserver().autoDispose(scopeProvider).subscribe {
            it.toast(this)
        }

        mViewModel.videoSub.hide().autoDispose(scopeProvider).subscribe {
            when (it) {
                //暂停
                1 -> {
                    binding.hTmnVideo.setPlayState(R.string.desc_video_resume_playback)
                    binding.hTmnVideo.gsyVideoManager.player.pause()

                    return@subscribe
                }
                //快进\快退
                2, 3 -> {
                    binding.hTmnVideo.setPlayState(R.string.desc_video_resume_playback)
                    binding.hTmnVideo.setMultipleVisibility(true)
                    return@subscribe
                }

                //关键帧播放
                4 -> {
                    binding.hTmnVideo.setPlayState(R.string.desc_video_resume_playback)
                    return@subscribe
                }
                //恢复播放
                5 -> {
                    binding.hTmnVideo.gsyVideoManager.player.start()
                    binding.hTmnVideo.setPlayState(R.string.desc_video_play_normal)
                    binding.hTmnVideo.setMultipleVisibility(false)
                    binding.hTmnVideo.setMultipleTitle(R.string.desc_video_multiple_one)
                    mViewModel.multiple = 1
                    return@subscribe
                }
                //拖动播放 、关闭
                else -> {
                    return@subscribe
                }
            }
        }
        mViewModel.videoToast.hide().autoDispose(scopeProvider).subscribe {
            binding.hTmnVideo.showProgress(false)

            binding.tvTmnVideoToast.text = UrlUtil.getToastMap()[it ?: "88"]
            binding.tvTmnVideoToast.visibility = View.VISIBLE
            binding.hTmnVideo.release()
            binding.hTmnVideo.startPlay.visibility = View.GONE
        }

        binding.hTmnVideo.setVideoAllCallBack(object : GSYSampleCallBack() {
            override fun onPlayError(url: String?, vararg objects: Any?) {
                super.onPlayError(url, *objects)
                binding.hTmnVideo.release()
                binding.hTmnVideo.startPlay.visibility = View.GONE
                mViewModel.getErrorState()
            }
        })
    }


    override fun onBackPressed() {
        mViewModel.stopPlay()
        binding.hTmnVideo.setVideoAllCallBack(null)
        super.onBackPressed()
    }

    override fun onDestroy() {
        super.onDestroy()
        binding.hTmnVideo.stopTime()
        binding.hTmnVideo.release()
        CustomVideoManager.instance.releaseAllVideos()
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            mViewModel.stopPlay()
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onPause() {
        super.onPause()
        binding.hTmnVideo.onVideoPause()
        CustomVideoManager.instance.onPause()
    }

    override fun onResume() {
        super.onResume()
        binding.hTmnVideo.onVideoResume()
        CustomVideoManager.instance.onResume()
    }

    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        window.decorView.systemUiVisibility =
            View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
                    View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
    }

    /////////////////////////////播放状态切换/////////////////////////////////////////////////////////
    private var measuredWidth: Int = 0
    private var measuredHeight: Int = 0
    private var playPopup: PopupWindow? = null
    private fun initPlayPopup() {
        val view = LayoutInflater.from(this).inflate(R.layout.popup_play_state, null)
        view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        measuredWidth = view.measuredWidth
        measuredHeight = view.measuredHeight
        playPopup = PopupWindow(
            view,
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT
        ).apply {
            isFocusable = true
//            isOutsideTouchable = true
            setBackgroundDrawable(ColorDrawable(0xffffffff.toInt()))
        }
        val group = view.findViewById<RadioGroup>(R.id.rdg_play_state)
        group.setOnCheckedChangeListener { group, checkedId ->
            if (checkedId == -1) return@setOnCheckedChangeListener
            when (checkedId) {
                R.id.rdb_play_state_pause -> {
                    mViewModel.pauseVideo()

                }
                R.id.rdb_play_state_fast -> {
                    mViewModel.fastVideo()

                }
                R.id.rdb_play_state_slow -> {
                    mViewModel.slowVideo()

                }
                R.id.rdb_play_state_frame -> {
                    mViewModel.frameVideo()

                }
            }
            playPopup?.dismiss()
            group.clearCheck()
        }

    }

    /////////////////////////////倍数切换/////////////////////////////////////////////////////////
    private var measuredMultipleWidth: Int = 0
    private var measuredMultipleHeight: Int = 0
    private var multiplePopup: PopupWindow? = null
    private fun initMultiplePopup() {
        val view = LayoutInflater.from(this).inflate(R.layout.popup_multiple_state, null)
        view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        measuredMultipleWidth = view.measuredWidth
        measuredMultipleHeight = view.measuredHeight
        multiplePopup = PopupWindow(
            view,
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT
        ).apply {
            isFocusable = true
//            isOutsideTouchable = true
            setBackgroundDrawable(ColorDrawable(0xffffffff.toInt()))
        }
        val group = view.findViewById<RadioGroup>(R.id.rdg_multiple)
        group.setOnCheckedChangeListener { group, checkedId ->
            if (checkedId == -1) return@setOnCheckedChangeListener
            when (checkedId) {
                R.id.rdb_multiple_one -> {
                    mViewModel.multipleVideo(1)
                    binding.hTmnVideo.setMultipleTitle(R.string.desc_video_multiple_one)
                }
                R.id.rdb_multiple_two -> {
                    mViewModel.multipleVideo(2)
                    binding.hTmnVideo.setMultipleTitle(R.string.desc_video_multiple_two)
                }
                R.id.rdb_multiple_four -> {
                    mViewModel.multipleVideo(4)
                    binding.hTmnVideo.setMultipleTitle(R.string.desc_video_multiple_four)
                }
                R.id.rdb_multiple_eight -> {
                    mViewModel.multipleVideo(8)
                    binding.hTmnVideo.setMultipleTitle(R.string.desc_video_multiple_eight)
                }
                R.id.rdb_multiple_sixteen -> {
                    mViewModel.multipleVideo(16)
                    binding.hTmnVideo.setMultipleTitle(R.string.desc_video_multiple_sixteen)
                }
            }
            multiplePopup?.dismiss()
            group.clearCheck()
        }

    }
}